#include "login.h"

//********************************************************************************
//用户登录
//********************************************************************************
void sendUserPasswd(int peerfd)
{
	// 1.发送用户名
	puts("请输入用户名");
	char username[50] = {0};
	scanf("%s", username);
	// 1.1发送登录指令
	int cmdtype = CMD_TYPE_LOGIN;
	send(peerfd, &cmdtype, 4, MSG_WAITALL);
	sendArray(peerfd, username, strlen(username));

	// 1.2验证用户名是否拥有
	int flag = -1;
	recv(peerfd, &flag, 4, 0);
	if (flag == 404)
	{
		printf("username not exits!\n");
		loginInServer(peerfd);
	}

	// 2.接收盐值
	int lenOfpass = 0;
	char salt[20] = {0};
	recvCircle(peerfd, (char *)&lenOfpass, 4);
	recvCircle(peerfd, salt, lenOfpass);

	printf("salt = %s\n", salt);
	// 3.输入密码，计算密文并传输
	puts("请输入密码");
	char passwd[100] = {0};
	scanf("%s", passwd);
	char *cryptograph = crypt(passwd, salt);
	printf("cryptograph = %s\n", cryptograph);
	sendMsg(peerfd, cryptograph);

	// 4.接收返回结果是否登陆成功
	recv(peerfd, &flag, 4, MSG_WAITALL);
	printf("flag = %d\n", flag);
	if (flag == 200)
	{
		printf("login success!\n");
	}
	else
	{
		printf("password error!\n");
		loginInServer(peerfd);
	}
}

//********************************************************************************
//选择登录或注册
//********************************************************************************
void loginInServer(int peerfd)
{
	do
	{
		char flag[2] = {0};
		printf("请选择：1.注册  2.登录\n");
		scanf("%s", flag);
		if(strcmp(flag,"1") == 0)
		{
			userRegister(peerfd); //无需break。
			printf("登录:\n");
			sendUserPasswd(peerfd);
		}
		else if(strcmp(flag,"2") == 0)
		{
			sendUserPasswd(peerfd);
			break;
		}
		else
		{
			printf("输入非法\n");
		}
	} while (1);
}

//********************************************************************************
//用户注册
//********************************************************************************
void userRegister(int peerfd)
{
	int flag = 0;
	// 1.发送指令类型
	int cmdType = CMD_TYPE_REG;
	send(peerfd, &cmdType, 4, MSG_WAITALL);
	// 1.1发送用户名
	puts("请输入用户名");
	char username[50] = {0};
	scanf("%s", username);
	sendArray(peerfd, username, strlen(username));
	recv(peerfd, &flag, 4, MSG_WAITALL);
	if (flag == 404)
	{
		printf("用户已存在\n");
		loginInServer(peerfd);
		return;
	}
	// 2.接收盐值
	char salt[22] = {0};
	int lengthOfSalt = 0;
	recvCircle(peerfd, (char *)&lengthOfSalt, 4);
	recvCircle(peerfd, salt, lengthOfSalt);

	// 3.输入密码
	printf("请输入密码:\n");
	char passwd[100] = {0};
	scanf("%s", passwd);

	// 4.生成密文并发送
	char *cryptograph = crypt(passwd, salt);
	printf("cryptograph = %s\n", cryptograph);
	sendMsg(peerfd, cryptograph);
}